﻿Imports System.Activities
Imports System.Management
Imports System.ComponentModel
Imports System.Drawing
Imports System.Activities.Presentation.Metadata
Imports System.Activities.Presentation

Public Class WMISYSShutdownPC
    Inherits WMIExecuteActivityBase

    Public Enum ShutdownValues As Integer
        Logoff = 0
        ForcedLogoff = 4
        Shutdown = 1
        ForcedShutdown = 5
        Reboot = 2
        ForcedReboot = 6
        Poweroff = 8
        ForcedPoweroff = 12
    End Enum


    Public Sub New()
        Me.DisplayName = My.Resources.ShutdownPCDisplayName
    End Sub

    Protected Overrides Function BeginExecute(ByVal context As AsyncCodeActivityContext, ByVal callback As AsyncCallback, ByVal state As Object) As IAsyncResult
        MyBase._target = "Win32_OperatingSystem"
        MyBase._where = ""
        MyBase._service = "cimv2"
        Return MyBase.BeginExecute(context, callback, state)
    End Function

    Protected Overrides Function ExecuteWMI(ByVal target As String, ByVal whereCondition As String, ByVal wmScope As ManagementScope) As List(Of Hashtable)
        Dim result As New List(Of Hashtable)
        Try
            wmScope = CreateScope(wmScope)

            Dim wmQuery As New ObjectQuery("SELECT * FROM " + target)
            Dim wmResult As New ManagementObjectSearcher(wmScope, wmQuery)
            For Each res As ManagementObject In wmResult.Get
                Dim inParams = res.GetMethodParameters("Win32Shutdown")
                inParams("Flags") = 1
                Dim outParams = res.InvokeMethod("Win32Shutdown", inParams, Nothing)
                If outParams IsNot Nothing Then
                    Dim resRec As New Hashtable
                    For Each resCol In outParams.Properties
                        If resCol.Value Is Nothing Then
                            resRec.Add(resCol.Name, Nothing)
                        Else
                            resRec.Add(resCol.Name, resCol.Value.ToString)
                        End If
                    Next
                    result.Add(resRec)
                End If
            Next
        Catch ex As Exception
            result.Clear()
        End Try
        Return result
    End Function

    Protected Overrides Sub CacheMetadata(metadata As CodeActivityMetadata)
        MyBase.CacheMetadata(metadata)

        Dim build As New AttributeTableBuilder
        'WMISYSShutdownPC Activity
        build.AddCustomAttributes(Me.GetType,
                                      New DesignerAttribute(GetType(WMIDefaultActivityDesigner), GetType(ActivityDesigner)),
                                      New ToolboxBitmapAttribute(Me.GetType, "WmiDefault.png"))

        MetadataStore.AddAttributeTable(build.CreateTable)
    End Sub

End Class
